package cn.rumoss.nettyinaction.transport;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * 
 * 	只用 JDK API 来实现 I/O 和 NIO。使用阻塞 IO 实现
 * 	这种阻塞模式在大连接数的情况就会有很严重的问题，如客
 * 户端连接超时，服务器响应严重延迟，性能无法扩展。
 * @author HeCG
 *
 */
public class PlainOioServer {

	public void serve(int port) throws IOException {
		
		final ServerSocket socket = new ServerSocket(port);
		
		try {
			for(;;) {
				
				final Socket clientSocket = socket.accept();
				/**
				 * 接收连接来自： Socket[addr=/127.0.0.1,port=6845,localport=8080]
				 * 接收连接来自： Socket[addr=/127.0.0.1,port=6846,localport=8080]
				 */
				System.out.println("PlainOioServer 接收连接来自： " + clientSocket);
				
				new Thread(new Runnable() {
					
					public void run() {
						
						OutputStream out;
						try {
							
							out = clientSocket.getOutputStream();
							out.write("Hi!\r\n".getBytes(Charset.forName("UTF-8")));
							out.flush();
							clientSocket.close();
							
						} catch (IOException e) {
							e.printStackTrace();
							try {
								clientSocket.close();
							} catch (Exception e2) {
								// TODO: handle exception
							}
						}
						
					}
					
				}).start();
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		PlainOioServer server = new PlainOioServer();
		server.serve(8080);
	}
	
}
